package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.gather.domain.*;
import com.erp.gather.domain.bo.ErpCollectProductSkuPriceBo;
import com.erp.gather.domain.vo.ErpCollectProductSkuPriceVo;
import com.erp.gather.mapper.*;
import com.erp.gather.service.IErpCollectProductSkuPriceService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.gather.api.domain.ErpCollectProduct;
import com.ruoyi.gather.api.domain.ErpCollectProductExpand;
import com.ruoyi.gather.api.domain.ErpCollectProductSku;
import com.ruoyi.gather.api.domain.ErpCollectProductSkuPrice;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * sku价格Service业务层处理
 *
 * @author erp
 * @date 2023-05-19
 */
@RequiredArgsConstructor
@Service
public class ErpCollectProductSkuPriceServiceImpl implements IErpCollectProductSkuPriceService {
    private final ErpCollectProductSkuPriceMapper baseMapper;
    private final ErpCollectProductMapper erpCollectProductMapper;
    private final ErpCollectProductExpandMapper erpCollectProductExpandMapper;
    private final ErpCollectProductSkuMapper erpCollectProductSkuMapper;
    private final ErpProductAreaMapper erpProductAreaMapper;

    /**
     * 批量删除sku价格
     */
    @Override
    public Boolean deleteWithValidByIds(List<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public ErpCollectProductSkuPrice getBySkuCode(String skuCode) {
        return baseMapper.selectOne(new LambdaQueryWrapper<ErpCollectProductSkuPrice>()
                .eq(ErpCollectProductSkuPrice::getSkuCode, skuCode).last("limit 1"));
    }

    /**
     * 查询sku价格列表
     */
    @Override
    public TableDataInfo<ErpCollectProductSkuPriceVo> queryPageList(ErpCollectProductSkuPriceBo bo,
                                                                    PageQuery pageQuery) {
        LambdaQueryWrapper<ErpCollectProductSkuPrice> lqw = buildQueryWrapper(bo);
        Page<ErpCollectProductSkuPriceVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询sku价格
     */
    @Override
    public ErpCollectProductSkuPriceVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpCollectProductSkuPrice entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 新增sku价格
     */
    @Override
    public Boolean insertByBo(ErpCollectProductSkuPriceBo bo) {
        ErpCollectProductSkuPrice add = BeanUtil.toBean(bo, ErpCollectProductSkuPrice.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改sku价格
     */
    @Override
    public Boolean updateByBo(ErpCollectProductSkuPriceBo bo) {
        ErpCollectProductSkuPrice update = BeanUtil.toBean(bo, ErpCollectProductSkuPrice.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    private LambdaQueryWrapper<ErpCollectProductSkuPrice> buildQueryWrapper(ErpCollectProductSkuPriceBo bo) {
        LambdaQueryWrapper<ErpCollectProductSkuPrice> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getSkuCode()), ErpCollectProductSkuPrice::getSkuCode, bo.getSkuCode());
        lqw.eq(StringUtils.isNotBlank(bo.getSkuPrice()), ErpCollectProductSkuPrice::getSkuPrice, bo.getSkuPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getAbsoluteQuoteMap()), ErpCollectProductSkuPrice::getAbsoluteQuoteMap,
                bo.getAbsoluteQuoteMap());
        return lqw;
    }


    @Override
    public void saveSkuPrice(Long productId) {
        System.out.println("productId：" + productId);

        // 判断是否有公共采集商品
        ErpCollectProduct product = erpCollectProductMapper.selectById(productId);
        if (product == null)
            return;

        // 获取sku
        List<ErpCollectProductSku> skuList = erpCollectProductSkuMapper
                .selectList(new LambdaQueryWrapper<ErpCollectProductSku>().eq(ErpCollectProductSku::getCollectProductId,
                        productId));

        Map<String, BigDecimal> skuMap = new HashMap<>();
        skuList.forEach(sku -> skuMap.put(sku.getSkuPropertyIds(),
                new BigDecimal(sku.getSkuPrice()).multiply(new BigDecimal(1.1))));

        // 创建skuprice的map
        Map<String, Map<String, BigDecimal>> skuPriceMap = new HashMap<>();

        Map<String, BigDecimal> skuPriceMinMap = new HashedMap<>();

        // 获取商品爬取的sku属性
        ErpCollectProductExpand expand = erpCollectProductExpandMapper
                .selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                        .eq(ErpCollectProductExpand::getCollectProductId, productId).last(" limit 1 "));

//		String productAttribute = expand.getProductAttribute();
//		if (!productAttribute.equals("0"))
//			productAttribute = "1";
        Integer templateId = expand.getTemplateId();

        String freightMap = expand.getFreightMap();
        List<Dict> freightMapList = JsonUtils.parseArrayMap(freightMap);

        Map<String, BigDecimal> skufreightMap = new HashMap<>();

        // 获取运费，修改金额
        for (Dict dict : freightMapList) {
            Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
            for (String key : absoluteQuoteMap.keySet()) {
                BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());

                skufreightMap.put(key + "-" + dict.getStr("shiptoCountry"), amount);

                // 添加sku价格
                if (skuPriceMinMap.containsKey(key)) {
                    BigDecimal price = skuPriceMinMap.get(key);
                    if (price.compareTo(amount) == 1)
                        skuPriceMinMap.put(key, amount);
                } else {
                    skuPriceMinMap.put(key, amount);
                }

                // 获取sku
                BigDecimal skuPrice = skuMap.get(key);

                // 计算最终价格
                amount = skuPrice.add(amount).setScale(2, BigDecimal.ROUND_HALF_UP);

                if (skuPriceMap.containsKey(key)) {
                    Map<String, BigDecimal> map1 = skuPriceMap.get(key);
                    map1.put(dict.getStr("shiptoCountry"), amount);
                } else {
                    Map<String, BigDecimal> map1 = new HashMap<String, BigDecimal>();
                    map1.put(dict.getStr("shiptoCountry"), amount);
                    skuPriceMap.put(key, map1);
                }
            }
        }

        List<ErpCollectProductSkuPrice> skuPriceList = new ArrayList<>();
        List<String> skucodeList = new ArrayList<String>();
        Map<String, Double> cacheMap = new HashMap<String, Double>();
        for (ErpCollectProductSku erpCollectProductSku : skuList) {

            String skuWeight = erpCollectProductSku.getSkuWeight().toString();
            String skuWidth = erpCollectProductSku.getSkuWidth().toString();
            String skuHeight = erpCollectProductSku.getSkuHeight().toString();
            String skuLength = erpCollectProductSku.getSkuLength().toString();

            skucodeList.add(erpCollectProductSku.getSkuCode());

            String skuPropertyIds = erpCollectProductSku.getSkuPropertyIds();
            BigDecimal minPrice = skuPriceMinMap.get(skuPropertyIds);

            // 获取sku
            BigDecimal skuPrice = skuMap.get(skuPropertyIds);

            // 计算最终价格
            BigDecimal amount = skuPrice.add(minPrice.multiply(new BigDecimal(1.5))).setScale(2,
                    BigDecimal.ROUND_HALF_UP);

            ErpCollectProductSkuPrice collectProductSkuPrice = new ErpCollectProductSkuPrice();

            collectProductSkuPrice.setCollectProductId(productId);
            collectProductSkuPrice.setSkuCode(erpCollectProductSku.getSkuCode());
            collectProductSkuPrice.setSkuPrice(amount.toString());
            Map<String, BigDecimal> map = skuPriceMap.get(skuPropertyIds);
            collectProductSkuPrice.setAbsoluteQuoteMap(JsonUtils.toJsonString(map));

            collectProductSkuPrice.setOriginalSkuPrice(skuPrice.setScale(2, BigDecimal.ROUND_HALF_UP).toString());

            //TODO 运费相关 转为内部类
            //获取支持的全球国家
//            List<ErpProductFreight> countryList = iErpProductFreightService.countryList();
//
//            Map<String, Double> globalFreightMap = new HashMap<>();
//            Map<String, BigDecimal> globalQuoteMap = new HashMap<>();
//
//            List<AeProductFreight> saveList = new ArrayList<AeProductFreight>();
//            for (ErpProductFreight freight : countryList) {
//                String countryCode = freight.getCountryCode();
//                String key = skuWeight + "-" + skuWidth + "-" + skuHeight + "-" + skuLength + "-" + "-" + skuLength
//                        + "-" + countryCode;
//
//                Double priceCalculator = 0d;
//                // 首先获取缓存map有值吗
//                priceCalculator = cacheMap.get(key);
//                if (priceCalculator == null) {
////						AeProductFreight aeProductFreight = aeProductFreightMapper.selectOne(
////								new LambdaQueryWrapper<AeProductFreight>().eq(AeProductFreight::getLength, skuLength)
////										.eq(AeProductFreight::getWeight, skuWeight)
////										.eq(AeProductFreight::getHeight, skuHeight)
////										.eq(AeProductFreight::getWidth, skuWidth)
////										.eq(AeProductFreight::getType, productAttribute)
////										.eq(AeProductFreight::getCountry, countryCode).last(" limit 1 "));
////						if (aeProductFreight != null) {
////							priceCalculator = aeProductFreight.getFreight().doubleValue();
////						} else {
//                    AeProductFreight aeProductFreight = new AeProductFreight();
//                    aeProductFreight.setCountry(countryCode);
//                    aeProductFreight.setWeight(skuWeight);
//                    aeProductFreight.setHeight(skuHeight);
//                    aeProductFreight.setWidth(skuWidth);
//                    aeProductFreight.setLength(skuLength);
//                    aeProductFreight.setType(templateId);
//                    BigDecimal calculateFreightByCaiNiao = commonProductFreightService
//                            .freightTrialByCaiNiao(aeProductFreight);
//                    if (calculateFreightByCaiNiao != null)
//                        priceCalculator = calculateFreightByCaiNiao.doubleValue();
//                    else
//                        priceCalculator = 0d;
//
//                    // 增加10%的费用
//                    priceCalculator = new BigDecimal(priceCalculator * 1.1).setScale(2, BigDecimal.ROUND_HALF_UP)
//                            .doubleValue();
//
////							if (priceCalculator != 0) {
//                    // 保存到数据库中
////								aeProductFreight = new AeProductFreight();
////								aeProductFreight.setCountry(countryCode);
////								aeProductFreight.setFreight(new BigDecimal(priceCalculator));
////								aeProductFreight.setHeight(skuHeight);
////								aeProductFreight.setLength(skuLength);
////								aeProductFreight.setWeight(skuWeight);
////								aeProductFreight.setWidth(skuWidth);
////								aeProductFreight.setType(Integer.valueOf(productAttribute));
////							aeProductFreightMapper.insert(aeProductFreight);
////								saveList.add(aeProductFreight);
////							}
////						}
//                    cacheMap.put(key, priceCalculator);
//                }
//
//                if (countryCode.equals("GB"))
//                    countryCode = "UK";
//                globalFreightMap.put(countryCode, priceCalculator);
//
//                // 计算区域定价
//                BigDecimal globalQuote = skuPrice.add(new BigDecimal(priceCalculator)).setScale(2,
//                        BigDecimal.ROUND_HALF_UP);
//                globalQuoteMap.put(countryCode, globalQuote);
//            }

            // 保存价格
//			aeProductFreightMapper.insertBatch(saveList);

//            collectProductSkuPrice.setFreightMap(JsonUtils.toJsonString(globalFreightMap));
//            collectProductSkuPrice.setGlobalQuoteMap(JsonUtils.toJsonString(globalQuoteMap));
//			System.err.println(collectProductSkuPrice);
            skuPriceList.add(collectProductSkuPrice);
        }
        // 先删除
        baseMapper.delete(new LambdaQueryWrapper<ErpCollectProductSkuPrice>()
                .in(ErpCollectProductSkuPrice::getCollectProductId, productId));
        // 在添加
        baseMapper.insertBatch(skuPriceList);
    }

    @Override
    public Map<String, Object> getSkuPriceByProIdAndTemId(Long productId, Integer templateId) {
        System.out.println("productId：" + productId);

        // 判断是否有公共采集商品
        ErpCollectProduct product = erpCollectProductMapper.selectById(productId);
        if (product == null)
            return null;

        // 获取商品爬取的sku属性
        ErpCollectProductExpand expand = erpCollectProductExpandMapper
                .selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
                        .eq(ErpCollectProductExpand::getCollectProductId, productId).last(" limit 1 "));

        // 获取sku
        List<ErpCollectProductSku> skuList = erpCollectProductSkuMapper
                .selectList(new LambdaQueryWrapper<ErpCollectProductSku>().eq(ErpCollectProductSku::getCollectProductId,
                        productId));

        // 获取国家
        List<ErpProductArea> selectList = erpProductAreaMapper.selectList();
        List<Object> list = new ArrayList<Object>();

        Map<String, Double> skuMap1 = new HashMap<String, Double>();

        for (ErpProductArea erpProductArea : selectList) {

            String areaNo = erpProductArea.getAreaNo();

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("shiptoCountry", areaNo);
            if (areaNo.equals("GB"))
                map.put("shiptoCountry", "UK");

            for (ErpCollectProductSku erpCollectProductSku : skuList) {
                String skuWeight = erpCollectProductSku.getSkuWeight().toString();
                String skuWidth = erpCollectProductSku.getSkuWidth().toString();
                String skuHeight = erpCollectProductSku.getSkuHeight().toString();
                String skuLength = erpCollectProductSku.getSkuLength().toString();

                String skuPropertyIds = erpCollectProductSku.getSkuPropertyIds();

                //TODO 运费相关 内部类调用
//                AeProductFreight aeProductFreight = new AeProductFreight();
//                aeProductFreight.setCountry(areaNo);
//                aeProductFreight.setWeight(skuWeight);
//                aeProductFreight.setHeight(skuHeight);
//                aeProductFreight.setWidth(skuWidth);
//                aeProductFreight.setLength(skuLength);
//                // 类型：标准0、特货1、纯电2、大包3等，参考字典表erp_product_template
//                aeProductFreight.setType(templateId);
//
//                Double priceCalculator = 0d;
//
//                BigDecimal calculateFreightByCaiNiao = commonProductFreightService
//                        .freightTrialByCaiNiao(aeProductFreight);
//                if (calculateFreightByCaiNiao != null)
//                    priceCalculator = calculateFreightByCaiNiao.doubleValue();
//                else {
//                    return null;
//                }
//                if (!priceCalculator.equals(0d)) {
//
//                    // 增加10%的费用
//                    priceCalculator = new BigDecimal(priceCalculator * 1.1).setScale(2, BigDecimal.ROUND_HALF_UP)
//                            .doubleValue();
//
//                }
//                skuMap1.put(skuPropertyIds, priceCalculator);

            }
            map.put("absoluteQuoteMap", skuMap1);
            list.add(map);
        }
        expand.setFreightMap(JsonUtils.toJsonString(list));

        // 创建skuprice的map
        Map<String, Map<String, BigDecimal>> skuPriceMap = new HashMap<>();

        Map<String, BigDecimal> skuPriceMinMap = new HashedMap<>();

        String freightMap = expand.getFreightMap();
        List<Dict> freightMapList = JsonUtils.parseArrayMap(freightMap);

        Map<String, BigDecimal> skufreightMap = new HashMap<>();

        Map<String, BigDecimal> skuMap = new HashMap<>();
        skuList.forEach(sku -> skuMap.put(sku.getSkuPropertyIds(),
                new BigDecimal(sku.getSkuPrice()).multiply(new BigDecimal(1.1))));

        // 获取运费，修改金额
        for (Dict dict : freightMapList) {
            Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
            for (String key : absoluteQuoteMap.keySet()) {
                BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());

                skufreightMap.put(key + "-" + dict.getStr("shiptoCountry"), amount);

                // 添加sku价格
                if (skuPriceMinMap.containsKey(key)) {
                    BigDecimal price = skuPriceMinMap.get(key);
                    if (price.compareTo(amount) == 1)
                        skuPriceMinMap.put(key, amount);
                } else {
                    skuPriceMinMap.put(key, amount);
                }

                // 获取sku
                BigDecimal skuPrice = skuMap.get(key);

                // 计算最终价格
                amount = skuPrice.add(amount).setScale(2, BigDecimal.ROUND_HALF_UP);

                if (skuPriceMap.containsKey(key)) {
                    Map<String, BigDecimal> map1 = skuPriceMap.get(key);
                    map1.put(dict.getStr("shiptoCountry"), amount);
                } else {
                    Map<String, BigDecimal> map1 = new HashMap<String, BigDecimal>();
                    map1.put(dict.getStr("shiptoCountry"), amount);
                    skuPriceMap.put(key, map1);
                }
            }
        }

        Map<String, Object> skuPriceResMap = new HashMap<>();
        List<String> skucodeList = new ArrayList<String>();
        for (ErpCollectProductSku erpCollectProductSku : skuList) {

            skucodeList.add(erpCollectProductSku.getSkuCode());

            String skuPropertyIds = erpCollectProductSku.getSkuPropertyIds();
            BigDecimal minPrice = skuPriceMinMap.get(skuPropertyIds);

            // 获取sku
            BigDecimal skuPrice = skuMap.get(skuPropertyIds);

            // 计算最终价格
            BigDecimal amount = skuPrice.add(minPrice.multiply(new BigDecimal(1.5))).setScale(2,
                    BigDecimal.ROUND_HALF_UP);

            ErpCollectProductSkuPrice collectProductSkuPrice = new ErpCollectProductSkuPrice();

            collectProductSkuPrice.setCollectProductId(productId);
            collectProductSkuPrice.setSkuCode(erpCollectProductSku.getSkuCode());
            collectProductSkuPrice.setSkuPrice(amount.toString());
            Map<String, BigDecimal> map = skuPriceMap.get(skuPropertyIds);
            collectProductSkuPrice.setAbsoluteQuoteMap(JsonUtils.toJsonString(map));

            skuPriceResMap.put(collectProductSkuPrice.getSkuCode(), collectProductSkuPrice);
        }

        return skuPriceResMap;
    }

}
